package com.heeexy.example.config.jwt;

import com.auth0.jwt.interfaces.Claim;
import com.heeexy.example.util.CommonUtil;
import com.heeexy.example.util.constants.ErrorEnum;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author Mingxian Ma
 * @description Jwt过滤器
 * @date 2020/5/25 18:23
 */
@WebFilter(filterName = "JwtFilter", urlPatterns = "/*",initParams = {
        @WebInitParam(name = "loginUI", value = "/login/auth"),
        @WebInitParam(name = "swaggerUI", value = "/swagger"),
        @WebInitParam(name = "apiDoc", value = "/api"),
})
public class JwtFilter implements Filter {
    private FilterConfig config;
    @Override
    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) req;
        final HttpServletResponse response = (HttpServletResponse) res;
        String loginUI = config.getInitParameter("loginUI");
        String swaggerUI = config.getInitParameter("swaggerUI").substring(1);
        String apiDoc = config.getInitParameter("apiDoc");
        String uri = request.getRequestURI();

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        //获取 header里的token
        final String token = request.getHeader("authorization");
        // 登录页面和wagger2界面放行
        if (uri.contains(loginUI) || uri.contains(swaggerUI) || uri.contains(apiDoc)) {
            response.setStatus(HttpServletResponse.SC_OK);
            chain.doFilter(request, response);
        }
        // Except OPTIONS, other request should be checked by JWT
        else {

            if (token == null) {
                response.getWriter().write(CommonUtil.errorJson(ErrorEnum.E_401).toString());
                return;
            }

            Map<String, Claim> userData = JwtUtil.verifyToken(token);
            if (userData == null) {
                response.getWriter().write(CommonUtil.errorJson(ErrorEnum.E_401).toString());
                return;
            }
            Integer userId = userData.get("userId").asInt();
            String userName = userData.get("userName").asString();
            String password = userData.get("password").asString();
            //拦截器 拿到用户信息，放到request中
            request.setAttribute("userId", userId);
            request.setAttribute("userName", userName);
            request.setAttribute("password", password);
            chain.doFilter(req, res);
        }
    }

    @Override
    public void destroy() {
    }
}
